<?php

namespace zhtfrontend\modules\sitepadapi\controllers;

use common\components\helpers\Fun;
use yii\data\ActiveDataProvider;
use zhtfrontend\modules\sitepadapi\components\rest\ActiveController;
use yii\data\ArrayDataProvider;
use yii\db\Query;
use yii\filters\Cors;
use yii\web\NotFoundHttpException;
use yii\web\Response;

class TeacherController extends ActiveController
{
    public $modelClass = 'zhtfrontend\models\datas\Teacher';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Allow-Origin' => ['*'],
                'Access-Control-Request-Method' => ['POST', 'PUT', 'GET', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 3600,
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],
        ];
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionIndex()
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find();
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }

    public function actionView($id)
    {
        return $this->findModel($id);
    }

    public function actionFindbytel($tel)
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find()->where(['tel' => $tel]);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }

    public function actionFindbycode($qrcode)
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find()->where(['qrcode' => $qrcode]);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }

    public function actionCreate()
    {
        $model = new $this->modelClass();
        $model->attributes = \Yii::$app->request->post();
        if (!$model->save()) {
            return array_values($model->getFirstErrors())[0];
        }
        return $model;
    }
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->attributes = \Yii::$app->request->post();
        if (! $model->save()) {
            return array_values($model->getFirstErrors())[0];
        }
        return $model;
    }

    protected function findModel($id)
    {
        $modelClass = $this->modelClass;
        if (($model = $modelClass::findOne($id)) !== null) {
            return $model;
        } else {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
    }

    /*
     * 获取老师对应的班主任们
     */
    public function actionGetheadteachers($teache_id){
        if(empty($teache_id)){
            try {
                throw new NotFoundHttpException('教师id不能为空');
            } catch (NotFoundHttpException $e) {
                return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $teacher = (new Query())->select('*')->from('{{%teacher}}')->where(['id'=>$teache_id])->one(Fun::getSiteDb());
        if(empty($teacher)){
            try {
                throw new NotFoundHttpException('不存在对应的教师');
            } catch (NotFoundHttpException $e) {
                return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $current_headteacher_arr = [];
        $other_headteachers_arr = [];
        if($teacher['parent_id']!=null){
            $current_headteacher = (new Query())->select('*')->from('{{%teacher}}')->where(['id'=>$teacher['parent_id'],'is_headmaster'=>1])->one(Fun::getSiteDb());
            $current_headteacher['current_headteacher'] = 1;//是否是对应的班主任
            $current_headteacher_arr[] = $current_headteacher;
        }
        if($teacher['cate_id']!=null){//获取同类型课程的所有班主任
            $other_headteachers_arr = (new Query())->select('*')->from('{{%teacher}}')->where(['cate_id'=>$teacher['cate_id'],'is_headmaster'=>1])->andWhere(['not', ['id' => $teacher['parent_id']]] )->all(Fun::getSiteDb());
        }

        $data = array_merge($current_headteacher_arr,$other_headteachers_arr);
        return ['statusCode' => 200, 'message' => 'success', 'items' => $data];
    }
    /*
     * 老师评价班主任
     * post提交过来班主任的id以及对应的得分作为个数组传过来
     */
    public function actionCommentonheadteacher($teache_id){
        $post_data = \Yii::$app->request->post();
        $this->getSiteDb(Fun::getSiteId());

        $commentArr = $commentRelationArr = [];
        foreach($post_data['commentScores'] as $dk=>$dv){
            $commentArr[] = [
                'object_type' => 3,
                'title' => '针对' . $dv['teacher_name'] . '班主任',
                'description' => $dv['content'],
                'object_id' => $dv['teacher_id'],//被评价的班主任
                'teacher_id' => $teache_id//进行评价的老师编号
            ];
            $have_comment = (new Query())->select('*')->from('{{%comment}}')->where(['teacher_id'=>$teache_id,'object_id'=>$dv['teacher_id'],'object_type'=>3])->one();
            if(empty($have_comment)){
                \Yii::$app->db->createCommand()->insert('{{%comment}}', [
                    'object_type' => 3,
                    'title' => '针对' . $dv['teacher_name'] . '班主任',
                    'description' => $dv['content'],
                    'object_id' => $dv['teacher_id'],
                    'teacher_id' => $teache_id
                ])->execute();
                $insertId = \Yii::$app->db->getLastInsertID();
                $comment_relation_info = $dv['comment_info'];
                if(!empty($comment_relation_info)){
                    foreach($comment_relation_info as $cri){
                        $commentRelationArr[] = [
                            'comment_id' => $insertId,
                            'comment_info_id' => $cri['comment_info_id'],
                            'for_value' => $cri['for_value']
                        ];
                    }
                }
            }else{
                if(!empty($comment_relation_info)){
                    $have_comment_relation = (new Query())->select('*')->from('{{%comment_relation}}')->where(['comment_id'=>$have_comment['id'],'comment_info_id'=>$comment_relation_info['comment_info_id']])->one();
                    if(!empty($have_comment_relation)){
                        \Yii::$app->db->createCommand()->update('{{%comment_relation}}', ['for_value' => $cri['for_value']], ['comment_id'=>$have_comment['id'],'comment_info_id'=>$cri['comment_info_id']])->execute();
                    }else{
                        $commentRelationArr[] = [
                            'comment_id' => $have_comment['id'],
                            'comment_info_id' => $cri['comment_info_id'],
                            'for_value' => $cri['for_value']
                        ];
                    }
                }

            }
        }
        \Yii::$app->db->createCommand()->batchInsert('{{%comment_relation}}', [
            'comment_id', 'comment_info_id', 'for_value'
        ], $commentRelationArr)->execute();
        return ['statusCode' => 200, 'message' => 'success', 'items' => $commentRelationArr];
    }

    /*获取当前老师的点评 数据库表comment太模糊了猜不出teacher_id和object_id在comment表中的含义，object_type=3的话就这么猜吧，teacher_id是进行评价的老师id，object_id是被评价的班主任老师id*/
    public function actionGetheadteachercomments($teache_id){
        $arr = $data = $comment_info_arr1 = [];
        $all_headteachers = $current_headteacher_arr = $other_headteachers_arr = [];
        $site_id = Fun::getSiteId();
        $teacher = (new Query())->select('*')->from('{{%teacher}}')->where(['id'=>$teache_id])->one(Fun::getSiteDb());
        if($teacher['is_headmaster'] == 1){
            $current_headteacher_arr = [];
            if(!empty($teacher['cate_id'])){
                $other_headteachers_arr = (new Query())->select('*')->from('{{%teacher}}')->where(['cate_id'=>$teacher['cate_id'],'is_headmaster'=>1])->andWhere(['not', ['id' => $teacher['parent_id']]] )->all(Fun::getSiteDb());
            }else{
                $other_headteachers_arr = [];
            }
            //$other_headteachers_arr = (new Query())->select('*')->from('{{%teacher}}')->where(['cate_id'=>$teacher['cate_id'],'is_headmaster'=>1])->andWhere(['not', ['id' => $teacher['parent_id']]] )->all(Fun::getSiteDb());
        }else{
            if($teacher['parent_id'] != null){
                $current_headteacher = (new Query())->select('*')->from('{{%teacher}}')->where(['id'=>$teacher['parent_id'],'is_headmaster'=>1])->one(Fun::getSiteDb());
                $current_headteacher['current_headteacher'] = 1;//是否是对应的班主任
                $current_headteacher_arr[] = $current_headteacher;
            }
            if($teacher['cate_id']!=null){//获取同类型课程的所有班主任
                $other_headteachers_arr = (new Query())->select('*')->from('{{%teacher}}')->where(['cate_id'=>$teacher['cate_id'],'is_headmaster'=>1])->andWhere(['not', ['id' => $teacher['parent_id']]] )->all(Fun::getSiteDb());
            }
        }

        $all_headteachers = array_merge($current_headteacher_arr,$other_headteachers_arr);
        if(!empty($all_headteachers)){
            $commentInfo = (new Query())->select('*')->from('{{%comment_info}}')->where(['object_type'=>3])->all(Fun::getSiteDb());
            foreach ($commentInfo as $kk => $vv) {
                $comment_info_arr1[] = [
                    'comment_info_id' => $vv['id'],
                    'comment_info_title' => '该员工的' . $vv['title']
                ];
            }

            foreach($all_headteachers as $headteacher){
                $comment = (new Query())->select('*')->from('{{%comment}}')->where(['object_type'=>3,'teacher_id'=>$teache_id,'object_id'=>$headteacher['id']])->one(Fun::getSiteDb());
                $comment_info_arr = [];
                if(!empty($comment)){
                    foreach ($comment_info_arr1 as $k=>$ci){
                        $commentRelation = (new Query())->select('*')->from('{{%comment_relation}}')->where(['comment_id'=>$comment['id'],'comment_info_id'=>$ci['comment_info_id']])->one(Fun::getSiteDb());
                        if(!empty($commentRelation)){
                            $ci['for_value'] = $commentRelation['for_value'];
                            $comment_info_arr[$k] = $ci;
                        }else{
                            $ci['for_value'] = 4;
                            $comment_info_arr[$k] = $ci;
                        }
                    }
                }else{//如果
                    foreach ($comment_info_arr1 as $k=>$ci){
                        $ci['for_value'] = 4;
                        $comment_info_arr[$k] = $ci;
                    }
                }
                $data[] = [
                    'teacher_id' => $headteacher['id'],
                    'teacher_name' => $headteacher['name'],
                    'title' => '针对' . $headteacher['name'] . '班主任,您的评价是:',
                    'comment_info' => $comment_info_arr,
                    'is_current_headteacher' => (isset($headteacher['current_headteacher'])&&$headteacher['current_headteacher']==1)?$headteacher['current_headteacher']:0
                ];
            }
        }

        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 20
            ],
            'sort' => [
                'attributes' => ['teacher_id']
            ]
        ]);
    }

    protected function getSiteDb($site_id)
    {
        $site_cache = Fun::cache('site_cache');
        foreach ($site_cache as $k => $v) {
            if ($site_id == $v['id']) {
                $site = $v['domain'];
            }
        }
        if ($site == null) return false;
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['db'])) return false;
        \Yii::$app->set('db', $site_cache[$site]['db']);
    }
}
